Implementing the Passive View -- a Derivative of the Model-View-Control


Introduction.

A while ago I wrote an article about the MVC pattern and just recently received a request for an example closer to a real-world implementation so I thought I would share the approach I have used in live projects.

There are a bunch flavors of MVC.  Here is an article by Martin Fowler about some of the differences if you really want to dig in. For this article, we'll be discussing building a passive view to keep the model and the view as "dumb"  as possible and avoid any dependencies between two.  The idea being that all of our implementation should lie in the control and not in the UI (the view).

So let's get started....

Part I. A Control Base Class

Since we'll be coding many different types of controllers for different views and models, it makes sense to pull the common functionality out into a base class and have the supertypes handle the parts that are different.  Using this technique we come up with what is called the "template pattern" for all you design pattern junkies out there.  The controller will need to keep references to both the view and the model and we'll be using an event driven architecture to wire things up.  What will happen, is the control will listen to events from the view and the model and be responsible for updating the view if the model changes and updating the model with change requests from the view.

 image002.gif

 A control will need references to both the view and the model and will also need a bunch of event handlers for notifications received from both the view and the model.  With our control base class, we don't know what the specific events will be to wire up from the concrete implementations of the view and model, so we'll create a few abstract methods as placeholders.  We'll eventually need to connect the three pieces (the model, view and control).  We'll do this using an Initialize() method that will be responsible for wiring all the connections between the control and it's model and view.  Just to keep things clean, we'll make this class disposable in order to unwire all the events if the object is explicitly disposed to avoid any unexpected behavior.

public abstract class MvcControlBase<TModel, TView> : IDisposable
{
    #region Member Variables

    protected TView m_view;
    protected TModel m_model;

    #endregion

    #region Abstract Methods

    protected abstract void WireEvents();
    protected abstract void UnwireEvents();
    protected abstract void SetViewState();

    #endregion

    #region Methods

    public virtual void Initialize(TModel model, TView view)
    {
        if (m_model != null || m_view != null)
            UnwireEvents();

        m_model = model;
        m_view = view;

        SetViewState();
        WireEvents();
    }

    #endregion

    #region Properties

    public TModel Model { get { return m_model; } }
    public TView View { get { return m_view; } }

    #endregion

    #region IDisposable Members

    public void Dispose()
    {
        UnwireEvents();
    }

    #endregion
}

Part II. The Control-View Wiring.

We need an object to carry the message from the view to the control when the view is requesting a change to a property of the model.  In order to do this, we'll be using a custom class derived from EventArgs that will carry the new value that has been requested by the view.

    public class PropertyChangeRequestEventArgs<T>:EventArgs
    {
        public PropertyChangeRequestEventArgs(T pRequestedValue)
        {
            RequestedValue = pRequestedValue;
        }

        public T RequestedValue { get; set; }
    }

Because we'll have a separate event for each property the view is expressing on the UI, we'll build a helper class to keep track of all the events in one handy object.  This is a bit tricky to do while keeping everything type safe because different properties have different types. The signature for this pool is below and the code is attached to his article and uses a similiar technique to the Generic Identity Map I wrote about in a previous article in order to consolidate objects of different types. 

image004.jpg

So now that we are done laying our foundations, let's look at constructing our MVC.

Part III. MVC Implementation

The Model

First, let's look at a simple model.  Let's say we have a "cat" object with "name" and "age" properties.  We want to be able to notify the control of any changes to these properties.  Luckily, these events are already built into the framework in the "System.ComponentModel" namespace. If you haven't dug into this namespace, it has a lot to offer in terms of building an event driven architecture. We'll use the pattern exposed by the INotifyPropertyChanged interface which dictates that we have one event (PropertyChangedEventHandler) that our model can use to expose property changes that our controller can listen to.    

public class CatModel: INotifyPropertyChanged
{

    #region Member Variables

    private String m_name;
    private Int32 m_age;
    private event PropertyChangedEventHandler m_propertyChanged;

    #endregion

    #region Properties

    public String Name
    {
        get { return m_name; }
        set
        {
            if(m_name != value)
            {
                m_name = value;

                // if there is a change... raise the event to notify the control
                if(null != m_propertyChanged)
                    m_propertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }

    public Int32 Age
    {
        get { return m_age; }
        set
        {
            if (m_age != value)
            {
                m_age = value;

                // if there is a change... raise the event to notify the control
                if (null != m_propertyChanged)
                    m_propertyChanged(this, new PropertyChangedEventArgs("Age"));
            }
        }
    }

    #endregion

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged
    {
        add{ m_propertyChanged += value; }
        remove{ m_propertyChanged -= value; }
    }

    #endregion
}

The Abstract View

Next, let's look at our view.  We'll be creating our view as an interface, so we are not tied to any one concrete view.    This way, any UI user component implementing our interface can be controlled by a controller.  The controller needs to be able to set the name and age in the view as well as register and un-register for change request events that the view will fire.

    public interface ICatView
    {
        String CatName { set; }
        Int32 CatAge { set; }
        void RegisterChangRequestListener<T>(String propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler);
        void UnRegisterChangRequestListener<T>(String propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler);
    }

The Controller

Finally, our controller class will be responsible for managing both the view and model.  All we have to do is implement our abstract MvcControlBase<CatModel, ICatView> class by building event handlers, wiring up the events, and making sure everything is initialized by calling Initialize() in the constructor.

public class CatControl: MvcControlBase<CatModel, ICatView>
{
    public CatControl(CatModel model, ICatView view)
    {
        Initialize(model, view);
    }

    protected override void WireEvents()
    {
        Model.PropertyChanged += Model_PropertyChanged;
        View.RegisterChangRequestListener<String>("Name", View_OnNameChangeRequest);
        View.RegisterChangRequestListener<Int32>("Age", View_OnAgeChangeRequest);
    }

    protected override void UnwireEvents()
    {
        Model.PropertyChanged -= Model_PropertyChanged;
        View.UnRegisterChangRequestListener<String>("Name", View_OnNameChangeRequest);
        View.UnRegisterChangRequestListener<Int32>("Age", View_OnAgeChangeRequest);
    }

    private void View_OnNameChangeRequest(Object sender, PropertyChangeRequestEventArgs<String> args)
    {
        Model.Name = args.RequestedValue;
    }

    private void View_OnAgeChangeRequest(Object sender, PropertyChangeRequestEventArgs<Int32> args)
    {
        Model.Age = args.RequestedValue;
    }

    private void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "Name":
                View.CatName = Model.Name;
                break;
            case "Age":
                View.CatAge = Model.Age;
                break;
            default:
                throw new ArgumentException("Property not handled: " + e.PropertyName);
        }
    }

    protected override void SetViewState()
    {
        View.CatAge = Model.Age;
        View.CatName = Model.Name;
    }
}

Of course, this is a very simplistic control where the control is doing nothing but handling the requests and updating the values in the view and model, but in the real world the control would probably have validation logic and/or business rules encapsulated as well.

Part IV. Concrete Views

We'll be building two windows "cat" views.  The first will display the name and age allow incrementing the age through a button.  The second will display the name in a textbox (so we can update it) and the age in a label.

image006.jpg

Both our views will use the ChangeRequestEvents that we briefly discussed earlier to hold an event pool for all the events the view can raise which makes wiring things up pretty easy.  As you can see from the code below, implementing the ICatView interface is pretty simple using the pool and just requires firing the appropriate event when we get event messages from the UI.

public partial class CatView1 : UserControl, ICatView
{
    #region Constructors

    public CatView1()
    {
        InitializeComponent();
        m_changeRequestedEvents = new ChangeRequestEvents(this);
    }

    #endregion

    #region Member Variables

    private ChangeRequestEvents m_changeRequestedEvents;

    #endregion

    #region Methods

    private void m_btnIncrementAge_Click(object sender, EventArgs e)
    {
        m_changeRequestedEvents.Fire<Int32>("Age", Int32.Parse(m_lblAge.Text) + 1);
    }

    #endregion

    #region ICatView Members

    public int CatAge
    {
        set
        {
            m_lblAge.Text = value.ToString();
        }
    }

    public string CatName
    {
        set { m_lblName.Text = value; }
    }

    public void RegisterChangRequestListener<T>(string propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler)
    {
        m_changeRequestedEvents.RegisterListener<T>(propertyName, handler);
    }

    public void UnRegisterChangRequestListener<T>(string propertyName, EventHandler<PropertyChangeRequestEventArgs<T>> handler)
    {
        m_changeRequestedEvents.UnRegisterListener<T>(propertyName, handler);
    }

    #endregion
}

The code for the other view is very similar so I won't put it here, but it is in the code attached to this article.

Part IV. Implementing the Concrete Views

Now that we have the views in place, we will place them on a form and wire them up as follows.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CatModel model = new CatModel() { Age = 10, Name = "Fluffy" };

        new CatControl(model, m_catView1); // wire up cat view 1
        new CatControl(model, m_catView2); // wire up cat view 2
    }
}

And that's it.  It might be a good idea to keep references to each control and explicitly dispose them when the form is disposed, but since this is the main form and process will close when the form closes, it wasn't crucial in this case.

Check out the project attached to this article and you'll notice that one of the cool things about using the MVC pattern is when the model is updated, ALL the view are updated because the model notifies all listening controls which then update their respective views.

image008.gif

There are many different flavors of the MVC that we can use to build our applications I just happen to particularly like the Passive View for it's clean separation of each component of the MVC pattern.  If you are interested in using the MVC for web applications, it is definitely worth checking out the new MVC web  framework.

Until next time,

Happy coding


Similar Articles